package com.example.oss.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class WebLogAspect {

    @Pointcut("execution(public * com.example.*.controller.*.*(..))")
    public void controllerLog() {
    }

    @Before("controllerLog()")
    public void logBeforeController(JoinPoint joinPoint) {
		// 这个RequestContextHolder是Springmvc提供来获得请求的东西
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        log.info("######## URL: [ {} ]", request.getRequestURL().toString());
        log.info("######## HTTP_METHOD: [ {} ]", request.getMethod());
        log.info("######## IP: [{}]", request.getRemoteAddr());
        log.info("######## THE ARGS OF THE CONTROLLER: [ {} ]", Arrays.toString(joinPoint.getArgs()));

        // 获取包+类名 获取方法名
        log.info("######## CLASS_METHOD: [ {} ]", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        // 需要加强的目标类的对象
        log.info("######## TARGET: [ {} ]", joinPoint.getTarget());
        // 经过加强后的代理类的对象
        log.info("######## THIS: [ {} ]", joinPoint.getThis());
    }

    @AfterReturning(returning = "returnOb", pointcut = "controllerLog()")
    public void doAfterReturning(Object returnOb) {
        log.info("######## RETURN_OBJECT: [ {} ]", returnOb);
    }
}
